package com.fengwk.user.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fengwk.support.exception.BaseException;
import com.fengwk.support.util.StringUtils;
import com.fengwk.user.face.model.User;
import com.fengwk.user.service.EncodeService;
import com.fengwk.user.service.RandomService;
import com.fengwk.user.service.RegisterService;
import com.fengwk.user.service.UserService;

@Service
public class RegisterServiceImpl implements RegisterService {

	@Autowired
	private UserService userService;
	@Autowired
	private RandomService randomService;
	@Autowired
	private EncodeService encodeService;
	
	@Transactional
	@Override
	public User register(Long avatarId, String username, String email, String mobilePhone, String password,
	        String nickName, String realName, String idCard, Integer sex, Long birthTime) {
		if (StringUtils.isBlank(username) && StringUtils.isBlank(email) && StringUtils.isBlank(mobilePhone)) {
			throw new BaseException("注册用户身份信息为空");
		}
		User user = userService.getUserByUsername(username);
		if (user == null) {
			user = userService.getUserByEmail(email);
			if (user == null) {
				user = userService.getUserByMobilePhone(mobilePhone);
				if (user == null) {
					password = encodeService.encodePassword(password);
					return userService.saveUser(avatarId, username, email, mobilePhone, password, nickName, realName, idCard, sex, birthTime);
				}
			}
		}
		throw new BaseException("注册用户信息已存在");
	}

	@Override
	public void resetPassword(String identity, String random, String password) {
		if (!randomService.checkRandom(identity, random))
			throw new BaseException("随机码校验失败");
		User user = getUserByIdentity(identity);
		if (user == null)
			throw new BaseException("用户[" + identity + "]不存在");
		password = encodeService.encodePassword(password);
		userService.updateUser(user.getUserId(), null, null, null, null, password, null, null, null, null, null, null);
	}
	
	@Override
	public boolean existUsername(String username) {
		return userService.getUserByUsername(username) != null;
	}

	@Override
	public boolean existEmail(String email) {
		return userService.getUserByEmail(email) != null;
	}

	@Override
	public boolean existMobilePhone(String mobilePhone) {
		return userService.getUserByMobilePhone(mobilePhone) != null;
	}
	
	private User getUserByIdentity(String identity) {
		User user = userService.getUserByUsername(identity);
		if (user == null) {
			user = userService.getUserByEmail(identity);
			if (user == null) {
				user = userService.getUserByMobilePhone(identity);
			}
		}
		return user;
	}

}
